package net.mingsoft.expertmanage.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.mingsoft.base.entity.ResultData;
import net.mingsoft.expertmanage.entity.ProjectEntity;
import net.mingsoft.expertmanage.service.IProjectService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 项目管理控制器
 */
@Api(value = "项目管理接口")
@RestController
@RequestMapping("/${ms.manager.path}/expertmanage/project")
public class ProjectController {

    private static final Logger LOG = LoggerFactory.getLogger(ProjectController.class);

    @Autowired
    private IProjectService projectService;

    /**
     * 查询项目列表
     */
    @ApiOperation(value = "查询项目列表")
    @GetMapping("/list")
    public ResultData list(@RequestParam(value = "pageNum", required = false, defaultValue = "1") int pageNum,
                            @RequestParam(value = "pageSize", required = false, defaultValue = "10") int pageSize,
                            @RequestParam(value = "keyword", required = false) String keyword) {
        Page<ProjectEntity> page = new Page<>(pageNum, pageSize);
        QueryWrapper<ProjectEntity> queryWrapper = new QueryWrapper<>();
        
        if (keyword != null && !keyword.isEmpty()) {
            queryWrapper.like("project_name", keyword).or()
                      .like("project_code", keyword).or()
                      .like("core_tech_keywords", keyword);
        }
        
        return ResultData.build().success(projectService.page(page, queryWrapper));
    }

    /**
     * 保存项目
     */
    @ApiOperation(value = "保存项目")
    @PostMapping("/save")
    public ResultData save(@RequestBody ProjectEntity project) {
        projectService.save(project);
        return ResultData.build().success();
    }

    /**
     * 更新项目
     */
    @ApiOperation(value = "更新项目")
    @PostMapping("/update")
    public ResultData update( ProjectEntity project) {
        projectService.updateById(project);
        return ResultData.build().success();
    }

    /**
     * 删除项目
     */
    @ApiOperation(value = "删除项目")
    @PostMapping("/delete/{id}")
    public ResultData delete(@PathVariable("id") Long id) {
        projectService.removeById(id);
        return ResultData.build().success();
    }

    /**
     * 批量删除项目
     */
    @ApiOperation(value = "批量删除项目")
    @PostMapping("/delete")
    public ResultData delete(@RequestBody List<Long> ids) {
        projectService.removeByIds(ids);
        return ResultData.build().success();
    }
    
    /**
     * 根据专家编号查询关联的项目
     */
    @ApiOperation(value = "根据专家编号查询关联的项目")
    @GetMapping("/getByExpert")
    public ResultData getByExpert(@RequestParam("expertCode") String expertCode) {
        if (StringUtils.isEmpty(expertCode)) {
            return ResultData.build().error("专家编号不能为空");
        }
        
        List<ProjectEntity> projects = projectService.getByExpertCode(expertCode);
        return ResultData.build().success(projects);
    }
    
    /**
     * 根据负责人编号查询项目
     */
    @ApiOperation(value = "根据负责人编号查询项目")
    @GetMapping("/getByLeader")
    public ResultData getByLeader(@RequestParam("leaderCode") String leaderCode) {
        if (StringUtils.isEmpty(leaderCode)) {
            return ResultData.build().error("负责人编号不能为空");
        }
        
        List<ProjectEntity> projects = projectService.getByLeaderCode(leaderCode);
        return ResultData.build().success(projects);
    }

    /**
     * 导入Excel数据
     */
    @PostMapping("/import")
    public ResultData importExcel(@RequestParam("file") MultipartFile file) {
        try {
            String result = projectService.importExcel(file);
            return ResultData.build().success(result);
        } catch (Exception e) {
            return ResultData.build().error(e.getMessage());
        }
    }

    /**
     * 根据编号获取项目信息
     */
    @GetMapping("/getByCode/{code}")
    public ResultData getByCode(@PathVariable String code) {
        return ResultData.build().success(projectService.getByProjectCode(code));
    }

    /**
     * 获取所有项目（不分页）
     */
    @GetMapping("/all")
    public ResultData getAll() {
        return ResultData.build().success(projectService.list());
    }

    /**
     * 下载导入模板
     */
    @GetMapping("/template")
    public void downloadTemplate(HttpServletResponse response) {
        try {
            // 重定向到RelationController的模板下载功能
            response.sendRedirect("../relation/importTemplate/project");
        } catch (IOException e) {
            LOG.error("模板下载失败", e);
        }
    }

    /**
     * 根据项目编号删除项目
     */
    @ApiOperation(value = "根据项目编号删除项目")
    @PostMapping("/deleteByCode/{code}")
    @Transactional(rollbackFor = Exception.class)
    public ResultData deleteByCode(@PathVariable String code) {
        try {
            if (StringUtils.isEmpty(code)) {
                return ResultData.build().error("项目编号不能为空");
            }
            
            // 1. 查找项目确认存在
            ProjectEntity project = projectService.getByProjectCode(code);
            if (project == null) {
                return ResultData.build().error("未找到对应项目信息");
            }
            
            // 2. 检查是否存在专家关联
            boolean hasExpertRelations = false;
            String leaderCode = project.getLeaderCode();
            String participantExperts = project.getParticipantExperts();
            
            if (!StringUtils.isEmpty(leaderCode) || !StringUtils.isEmpty(participantExperts)) {
                hasExpertRelations = true;
                LOG.info("项目{}存在专家关联关系，将一并清除", code);
            }
            
            // 3. 删除项目
            QueryWrapper<ProjectEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("project_code", code);
            boolean result = projectService.remove(queryWrapper);
            
            if (result) {
                LOG.info("成功删除项目: {}", code);
                if (hasExpertRelations) {
                    return ResultData.build().success("项目删除成功，相关专家关联已解除");
                } else {
                    return ResultData.build().success("项目删除成功");
                }
            } else {
                return ResultData.build().error("删除项目失败");
            }
        } catch (Exception e) {
            LOG.error("根据编号删除项目时发生错误: " + e.getMessage(), e);
            return ResultData.build().error("删除失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除项目
     */
    @PostMapping("/batchDelete")
    public ResultData batchDelete(@RequestBody List<String> projectCodes) {
        try {
            if (projectCodes == null || projectCodes.isEmpty()) {
                return ResultData.build().error("项目编号列表不能为空");
            }
            
            QueryWrapper<ProjectEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("project_code", projectCodes);
            boolean result = projectService.remove(queryWrapper);
            
            if (result) {
                return ResultData.build().success("批量删除成功");
            } else {
                return ResultData.build().error("批量删除失败");
            }
        } catch (Exception e) {
            LOG.error("批量删除项目时发生错误", e);
            return ResultData.build().error("删除失败: " + e.getMessage());
        }
    }
} 